package com.xwh.b2c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.xwh.b2c.dto.CategoryPageQueryDTO;
import com.xwh.b2c.entity.Category;
import com.xwh.b2c.entity.Member;
import com.xwh.b2c.exceptions.BusinessException;
import com.xwh.b2c.mapper.CategoryMapper;
import com.xwh.b2c.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xwh.b2c.vo.CategoryPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品分类表 服务实现类
 * </p>
 *
 * @author xoox
 * @since 2025-07-10
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Override
    public IPage<CategoryPageVO> getPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //todo 查询visibility
        wrapper.like(StringUtils.hasText(categoryPageQueryDTO.getName()),Category::getName,categoryPageQueryDTO.getName());
        Page<Category> page = this.page(new Page<>(categoryPageQueryDTO.getCurrent(), categoryPageQueryDTO.getPageSize()), wrapper);

        List<Category> records = page.getRecords();

        //注意Category和 CategoryVO中的数据类型保持一致

        Page<CategoryPageVO> pageVO = new Page<>();
        List<CategoryPageVO> pageVOList = new ArrayList<>();
        for (Category record : records) {
            CategoryPageVO categoryPageVO = new CategoryPageVO();
            BeanUtils.copyProperties(record, categoryPageVO);
            pageVOList.add(categoryPageVO);
            log.info("Category:{}",record);
            log.info("CategoryPageVO:{}",categoryPageVO);
        }

        pageVO.setRecords(pageVOList);
        log.info("impl: page:{}",records);
        log.info("impl: pageVO:{}",pageVOList);
        return pageVO;
    }

    @Override
    public void enable(Category category) {
        if(category == null){
            throw new BusinessException("用户不存在");
        }
        Boolean updateStatus = !category.getVisibility();
        category.setVisibility(updateStatus);

        this.updateById(category);
    }
}
